<template>
  <!-- 需求申请-->
  <div class="container">
    <el-row class="">
      <el-col :span="16" align="left">
        <el-input v-model="data.params.projectName" placeholder="项目名称" style="width: 150px; margin-right: 15px" clearable/>
        <el-button color="#626aef" @click="search()" class="ordinary">搜索</el-button>
      </el-col>

      <el-col :span="8" align="right">
<!--        <el-button class="ordinary" @click="getExport()" v-limit="'XMZX:SZXMLXPS:XQSQ:EXPORT'">批量导出</el-button>-->
        <el-button class="ordinary" @click="handleExport()" v-limit="'XMZX:SZXMLXPS:XQSQ:EXPORT'"> 批量导出</el-button>
        <el-button type="danger" @click="handleDetect()"  v-limit="'XMZX:SZXMLXPS:XQSQ:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'XMZX:SZXMLXPS:XQSQ:REAPP'">需求申请</el-button>
        <el-button class="lock" @click="getLock()" v-limit="'XMZX:SZXMLXPS:XQSQ:SUBMIT'">提交</el-button>
      </el-col>
    </el-row>

    <div>
      <Table class="table_" :tableArr="data.allTableData"  :columns="data.columns" @delectTable="delectIds" :pagination="data.page"
        :total="data.page.total"   @row-click="handleRowClick">
        <template #operate="{ row }">
          <el-button size="small" class="ordinary" v-if="row.status == '待确认'" :disabled="row.isLock == 1" @click="handleEdit(row,'edit')" v-limit="'XMZX:SZXMLXPS:XQSQ:EDIT'">编辑</el-button>
          <el-button size="small" class="ordinary" :disabled="row.isLock == 1" @click="handleEdit(row,'detail')" v-limit="'XMZX:SZXMLXPS:XQSQ:DETAILS'">详情</el-button>
        </template>
      </Table>

      <div class="example-pagination-block">
            <el-pagination
              :current-page="data.params.current"
              :page-size="data.params.size"
              :page-sizes="[10, 20, 30, 40,50,100]"
              background
              layout="prev, pager, next ,total,sizes,jumper"
              :total="data.page.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
      </div>
    </div>

    <el-dialog v-model="data.dialogVisible" width="60%" :show-close="false" @closed="handleCloseDialog">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="first">
              <Information :dialogType="data.dialogType" ref="getAssociation" :detailForm="detailForm" v-if="data.dialogVisible" @valueFlag="valueFlag"></Information>
            </el-tab-pane>

            <el-tab-pane label="相关附件" name="third" v-if="data.dialogType == 'edit'" >
              <platformFiles :files="data.files" @dataChange="dataChange" @filesParams="filesParams" :filesTypeFlag="false" :isExamine="true"
                download="XMZX:SZXMLXPS:XQSQ:DOWNLOAD"  upload="XMZX:SZXMLXPS:XQSQ:UPLOAD" fileDelete="XMZX:SZXMLXPS:XQSQ:FILEDELETE"
              ></platformFiles>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="third"  v-if="data.dialogType != 'edit'" >
              <platformFilesxq :files="data.files" @dataChange="dataChange" @filesParams="filesParams" :filesTypeFlag="false" :isExamine="true"
                download="XMZX:SZXMLXPS:XQSQ:DOWNLOAD"  upload="XMZX:SZXMLXPS:XQSQ:UPLOAD" fileDelete="XMZX:SZXMLXPS:XQSQ:FILEDELETE"
              ></platformFilesxq>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">关闭</el-button>
          <el-button type="primary" @click="handleSave()" v-show="data.dialogType != 'detail'">保存</el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 导出字段选择 -->
    <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
    ></Export>
  </div>
</template>
<script lang="ts">
import Information from '@/views/project/digit/requirementApplication/information.vue'
import {
  deleteInnovativeTalentTeam,
  getAddInnovativeTalentTeam,
  getExportInnovativeTalentTeam,
  getExportInnovativeTalentTeam1,
  getInnovativeTalentTeamDetail,
  getInnovativeTalentTeamList,
  getInnovativeTalentTeamLock,
  getUpdateInnovativeTalentTeam,
} from '@/views/science/api/digit'
import Members from '@/views/science/components/members/members.vue'
import platformFiles from '@/views/science/components/platformFiles/platformFiles.vue'
import platformFilesxq from '@/views/science/components/platformFiles/platformFilesxq.vue'
import record from '@/views/science/components/record/record.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals, tips } from '@/views/science/components/tips/tips'
import {ElMessage, ElMessageBox, UploadProps} from "element-plus"
import { computed, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import tableData from './tableHeader.json'
import {getExportApply} from "@/views/project/api/projectApplication";
import Export from '@/views/project/components/Export/index.vue'

export default {
  components: {
    SelectOption,
    Table,
    Information,
    Members,
    platformFiles,
    platformFilesxq,
    record,Export,
  },
  setup() {
    const store = useStore()
    const activeName = ref('first')
    const pagination = reactive({  //分页器信息
      pageSize:10,
      currentPage:1,
    })
    //分页操作
    const handleSizeChange = (val) =>{
      data.params.current = 1
      data.params.size = val
      tableList()
    }
    const handleCurrentChange = (val) =>{
      data.params.current = val
      tableList()
    }
    let data = reactive({
      detailId:'',
      dialogVisible: false,
      addFlag: 0,
      recordShow: false,
      loading: false,
      page: { page: 1, limit: 10, total: 4 },
      params: {
        projectName: "",
        current: 1,
        size: 10,
        unitId:'',
        teamLevelId:'',
      },
      selectedRows: [],
      columns: tableData.platformTableHeader,
      ids: [],
      allTableData: [],
      orgAllList: computed(() => store.state.technologyStrength.orgAllList),
      levelOptions: computed(() => store.state.innovativeTalents.cxlevelSelect),
      members: [],
      files: [],
      changeLogs: [],
      flag: null,

      baseInfo: [],
      memberList: [],
      fileList: [],
      dialogType:'edit',//弹框状态
      exportDialog: false,
      detailList: [] as any,
    });
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      // let sdt = selectArr.map((el) => el.id);
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          // exportProjectList({ ...searchParams, ids: sdt.join(",") , headList: arr }, '科研项目数据表格')
          getExportInnovativeTalentTeam1({ ...data.params, ids: data.ids , headList: arr}, "需求申请");
          console.log('批量导出')
          data.exportDialog = false;


        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'applyUnitName', title: '申报单位' },
        { fieldName: 'buildBudget', title: '建设预算 (万元)' },
        { fieldName: 'buildContent', title: '建设内容' },
        { fieldName: 'buildTarget', title: '建设目标' },
        { fieldName: 'needDeptSuggest', title: '需求部门意见' },
/*        { fieldName: 'applyPeople', title: '申请人' },
        { fieldName: 'applyPeopleName', title: '申请人姓名' },
        { fieldName: 'researchcontents', title: '主要研究内容' },
        { fieldName: 'mainindicators', title: '主要技术经济指标' },
        { fieldName: 'describetwo', title: '创新点及可能获得的成果和知识产权' },
        { fieldName: 'backdrop', title: '立项背景' },
        { fieldName: 'analysis', title: '国内外研究概况及可行性分析' },
        { fieldName: 'qualification', title: '项目研究的主要内容及技术指标' },
        { fieldName: 'roadmap', title: '项目研究的技术路线' },
        { fieldName: 'forecast', title: '推广应用前景及经济效益预测' },
        { fieldName: 'dividethework', title: '申报单位和协作单位及分工' },
        { fieldName: 'programme', title: '项目进度计划' },*/
      ]
    }
    interface Config {
      id: string;
    }
    let selectArr: Config[] = reactive([]);
    const handleSelectionChange = (val) => {
      selectArr = val;
    };


    const value = ref('2021-10-29')
    const holidays = [
      '2021-10-01',
      '2021-10-02',
      '2021-10-03',
      '2021-10-04',
      '2021-10-05',
      '2021-10-06',
      '2021-10-07',
    ]

    const isHoliday = ({ dayjs }) => {
      return holidays.includes(dayjs.format('YYYY-MM-DD'))
    }

    //主页面表格初始化
    const tableList = async () => {
      let res = await getInnovativeTalentTeamList(data.params)
      if (res.data.success) {
        let records = res.data.data
        records.records.map((item) => {
          if (item.status == 0) {
            item.status = "待确认"
          } else {
            item.status = "已确认"
          }

        })
        data.allTableData = records.records
        data.page.total = records.total
      }
    }

    let detailForm = reactive({})
    //详情数据获取
    const detailData = async (id) => {
      let res = await getInnovativeTalentTeamDetail(id)
      if (res.data) {
        store.commit('innovativeTalents/getTalentTeamInfo', { ...res.data.data })
        detailForm = res.data.data
        console.log('详情数据获取',detailForm);
        // data.members = res.data.data.members
        data.files = res.data.data.needAttachment || []
        // data.changeLogs = res.data.data.changeLogs
      }
    }

    const changeValue = (item) => data.params.unitId = item.id
    const changeValue1 = (item) => data.params.teamLevelId = item.itemValue


    const delectIds = (ids) => {
      data.ids = ids
    }

    const valueFlag = (flag) => {
      data.flag = flag
    }

    const paramsChange = (params) => {
      data.memberList = params
    }

    const filesParams = (params) => {
      console.log('params',params);
      data.files = params
    }

    //提交
    const getLock = async () => {
      if (data.ids.length != 0) {
        Modals('是否提交选择内容', '提示', 'warning').then(async () => {
          let res = await getInnovativeTalentTeamLock({ids:data.ids})
          if (res.data.success) {
            tips('提交成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })

      } else if (data.ids.length == 0) {
        tips('请选择', 'warning')
      }
    }

    const getExport = async () => {
      Modals('是否导出全部数据', '提示', 'warning').then(async () => {
        await getExportInnovativeTalentTeam({projectName:data.params.projectName})
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    const handleDetect = async () => {
      if (data.ids.length) {
        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          let res = await deleteInnovativeTalentTeam({ids:data.ids})
          if (res.data.success) {
            tips('删除成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })

      } else {
        tips('请选择', 'warning')
      }
    }
    //暂时没用
    const dataChange = () => {
      detailData(store.state.innovativeTalents.rowId)
    }

    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      data.page.page = 1
      tableList()
    }

    const handleAdd = () => {
      data.dialogType = 'edit'
      data.dialogVisible = true
      data.addFlag = 0
      data.files = []
      store.commit('innovativeTalents/emptytalentTeamInfo')
    }
    const handleRowClick = (row) => {
      handleEdit(row,'detail')
    }

    const handleEdit = (row,type) => {
      data.dialogType = type
      data.detailId = row.id
      detailData({id:row.id})
      data.dialogVisible = true
      data.addFlag = 1
      store.commit('innovativeTalents/getRowId', row.id)
    }

    const getAssociation = ref()
    const handleSave = async () => {
      const form = store.state.innovativeTalents.talentTeamInfo
      getAssociation.value.submitForm()
      if (!data.flag) {
        return
      }
      if (data.files.length >5){
        tips('最多上传5个文件', 'warning');
        return;
      }
      const params = {
        projectName: form.projectName,
        applyUnit: form.applyUnit,
        applyUnitName: form.applyUnitName,
        buildBudget: form.buildBudget,
        buildContent: form.buildContent,
        buildTarget: form.buildTarget,
        needDeptSuggest: form.needDeptSuggest,
        needAttachment:data.files
      }
      let res
      if (data.addFlag == 0) {
        res = await getAddInnovativeTalentTeam(params)
      } else {
        const paramss = {
          id:data.detailId,
          projectName: form.projectName,
          applyUnit: form.applyUnit,
          applyUnitName: form.applyUnitName,
          buildBudget: form.buildBudget,
          buildContent: form.buildContent,
          buildTarget: form.buildTarget,
          needDeptSuggest: form.needDeptSuggest,
          needAttachment:data.files,
        }
        res = await getUpdateInnovativeTalentTeam(paramss)
      }
      if (res.data.success) {
        console.log(res)
        data.dialogVisible = false
        activeName.value = 'first'
        tableList()
      }
    }

    const handleCloseDialog = () => {
      data.dialogVisible = false;
      data.recordShow = false;
      activeName.value = 'first'
    }


    //文件上传
    const handleChange: typeof UploadProps['onChange'] = (uploadFile, uploadFiles) => {
      console.log(uploadFile, uploadFiles)
    }
    const handleSuccess: typeof UploadProps['onSuccess'] = (uploadFile,uploadFiles,fileList) => {
      if (uploadFile.code == 200) {
        tips('上传成功', 'success')
        console.log('uploadFile',fileList)
        data.files = fileList
        // fileList.forEach(e =>{
        //   console.log('e',e.response.data.fileId);
        // })
      } else {
        tips('上传失败', 'error')
      }
    }
    //点击已上传的文件
    const addPreview = (file) =>{
      console.log('点击已上传的文件',file);

    }
    const handleError: typeof UploadProps['onError'] = (uploadFile) => {
      tips('上传失败', 'error')
    }
    const handleExceed: typeof UploadProps['onExceed'] = (files, uploadFiles) => {
      ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
        } totally`
      )
    }


    const cookie = () => localStorage.getItem('token')
    tableList()
    return {
      pagination,
      handleSizeChange,
      handleCurrentChange,
      data,
      activeName,
      valueFlag,
      getAssociation,
      paramsChange,
      filesParams,

      changeValue,
      changeValue1,
      delectIds,
      getLock,
      getExport,
      handleDetect,
      handleAdd,
      dataChange,
      handleCloseDialog,

      handleEdit,
      search,
      handleSave,
      detailForm,
      //附件相关
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      handleExceed,
      handleChange,
      handleSuccess,
      addPreview,

      closeExport,
      handleFiled,
      handleExport,
      handleRowClick,
    }
  },
}
</script>

<style lang="scss">
.table_{
  .el-pagination {
      display: none;
    }
}
</style>
<style lang="scss" scoped>
.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}

:deep(.el-pagination .btn-prev .el-icon) {
  margin: 0 auto;
}
.container {
  background-color: white;
  padding: 20px;
}

:deep(.el-dialog__body) {
  display: none;
}

// .el-col {
//   line-height: 40px;
// }

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */
</style>
